package com.htfyun.ft.fragment.factory;

import android.os.Bundle;
import android.os.StatFs;
import android.text.format.Formatter;
import android.view.View;
import android.widget.TextView;

import com.htfyun.ft.R;
import com.htfyun.ft.common.SDCardInfo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class FragmentSDCard extends FactoryBaseFragment {

    private SDCardInfo sdCardInfo;

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_factory_sdcard;
    }

    @Override
    protected void onInitView(@Nullable Bundle savedInstanceState) {
        super.onInitView(savedInstanceState);

        sdCardInfo = new SDCardInfo(getActivity());
        setBtnPassVisibility(View.GONE);
    }

    @Override
    protected void onVisible () {
        super.onVisible();
        sdCardInfo.startMonitor(onSDCardStatChangedListener);
    }

    @Override
    protected void onInvisible() {
        super.onInvisible();
        sdCardInfo.stopMonitor();

    }

    private void updateStatus(String status) {
        TextView txtStatus = (TextView) findViewById(R.id.txtStatus);
        if (txtStatus != null) {
            txtStatus.setText(status);
        }
    }

    private SDCardInfo.OnSDCardStatChangedListener onSDCardStatChangedListener =
            new SDCardInfo.OnSDCardStatChangedListener() {
                @Override
                public void onSDCardStatChangedListener(@NonNull SDCardInfo info, @Nullable StatFs statFs) {

                    if (statFs == null || !info.isSDCardMounted()) {
                        String unmounted = getString(R.string.status_unmounted);
                        String status = getString(R.string.sdcard_status, unmounted);
                        updateStatus(status);
                    } else {
                        String unmounted = getString(R.string.status_mounted);
                        String status = getString(R.string.sdcard_status, unmounted);

                        String stat = getString(R.string.sdcard_stat,
                                Formatter.formatFileSize(getActivity(), statFs.getTotalBytes()),
                                Formatter.formatFileSize(getActivity(), statFs.getFreeBytes()));

                        updateStatus(status + "\n" + stat);

                        delayAutoPass();

                    }
                }
            };

}
